<template>
	<!-- 添加图片弹窗 -->
	<div style="margin:12px;">
		<el-upload
      :action="serverUrl"
      :data="fileUpload"
      :show-file-list="false"
      :before-upload="uploadBefore"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      >
      <div slot="default" class="upload-btn">
        <i class="el-icon-plus"></i>
      </div>
			
		</el-upload>
	</div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
export default {
  data() {
    return {
      isDev:process.env.NODE_ENV == 'development',
      fileUpload: { //附件上传
        file: null,
        token:''
      },
      serverUrl: 'http://upload.qiniup.com', //上传图片的地址
      qiniuaddr:'https://qiniuoss.chenxi618.com',
      tempSrc:'',
      tempMediaId:'',
    }
  },
  computed:{
    ...mapState(['draftImage',]),
  },
  components: {
  },
  methods: {
    uploadBefore(file) {
      if(file.type != "image/png" && file.type != "image/jpeg") {
        this.$message({
          message: '请上传正确的图片',
          type: 'warning'
        });
        return false;
      }
      this.fileUpload.file = file;
      return this.$api.getQiniuToken().then(res=>{
        this.fileUpload.token = res.data.data;
      })
    },// 上传之前回调
    uploadSuccess(response,file,fileList){
      if(!("key" in response)){ return }
      let self = this;
      self.tempSrc = `${this.qiniuaddr}/${response.key}`;

      let arg = Object.assign(
        this.$store.getters.getESID(false),
        {
          mediaType:'image',
          mediaName:'',//传文件的时候，需要这个mediaName，要带上前名后缀的文件名
          qiniuUrl:`${this.qiniuaddr}/${response.key}`
        }
      );
      this.$api.getGetMediaId(arg).then((res)=>{
        self.tempMediaId = res.data.data;
        return {
          imgUrl:self.tempSrc,
          media_Id:self.tempMediaId,
        }
      }).then((res)=>{
        this.$store.commit("setDraft",{
          type:'image',
          obj:res
        })
      })
    },// 上传成功
    uploadError() {
      this.$message.error(`图片上传失败`)
    },
  },
  mounted() {},
}
</script>

<style lang="less" scoped>
.upload-btn{
  text-align: center;
  line-height:100px;
  width:100px;height:100px;
  border:1px dashed #999;
}
</style>
